import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getLoginUserUsingGet, getUserInterviewRoleUsingGet, userLogoutUsingPost } from '@/api/userController'
import ACCESS_ENUM from '@/access/accessEnum'

/**
 * 用户信息类型
 */
export interface LoginUser {
  id?: number
  userAccount?: string
  userName?: string
  userRole?: string
  userAvatar?: string
  company?: string
}

/**
 * 用户登录状态存储
 */
export const useLoginUserStore = defineStore('loginUser', () => {
  // 当前登录用户信息
  const loginUser = ref<LoginUser>({})
  // 当前用户面试身份(0-实习生 1-校招)
  const userInterviewRole = ref<number>()

  /**
   * 获取当前登录用户||招聘者||管理员信息
   */
  const fetchLoginUser = async () => {
    try {
      const res = await getLoginUserUsingGet()
      if (res.code === 0 && res.data) {
        //赋值
        loginUser.value = res.data as any
      } else {
        // 没有登录
        loginUser.value = {
          userRole: ACCESS_ENUM.NOT_LOGIN,
        }
      }
    } catch (error) {
      console.error('获取登录用户失败', error)
    }
  }

  const fetchUserInterviewRole = async () => {
    const data = await getUserInterviewRoleUsingGet()
    if(data.code === 0){
      userInterviewRole.value = data.data as any
    }else {
      userInterviewRole.value = -1
    }
  }

  /**
   * 设置登录用户信息
   * @param user - 用户信息
   */
  const setLoginUser = (user: LoginUser) => {
    loginUser.value = user
  }

  /**
   * 退出登录，清除用户信息
   */
  const logout = async () => {
    loginUser.value = {
      userRole: ACCESS_ENUM.NOT_LOGIN,
    }
    userInterviewRole.value = -1
    //清除session数据
    await userLogoutUsingPost()
  }

  /**
   * 判断用户是否登录
   */
  const isLoggedIn = () => {
    return !!loginUser.value.id
  }

  /**
   * 判断用户是否拥有指定角色
   * @param role - 角色类型
   */
  const hasRole = (role: string) => {
    return loginUser.value.userRole === role
  }

  /**
   * 判断用户是否为管理员
   */
  const isAdmin = () => {
    return loginUser.value.userRole === 'admin'
  }

  /**
   * 判断用户是否为招聘者
   */
  const isRecruiter = () => {
    return loginUser.value.userRole === 'recruiter'
  }

  /**
   * 判断用户是否为普通用户
   */
  const isUser = () => {
    return loginUser.value.userRole === 'user'
  }

  return {
    loginUser,
    userInterviewRole,
    fetchLoginUser,
    fetchUserInterviewRole,
    setLoginUser,
    logout,
    isLoggedIn,
    hasRole,
    isAdmin,
    isRecruiter,
    isUser,
  }
})
